﻿using System;
using System.Collections.Generic;
using UM_SERVER.Packet.InPacket;
using UM_SERVER.ProcessModel;
using System.Text;
using UM_SERVER.Triggers.TriggerObject;
using UM_SERVER.Timer;

namespace UM_SERVER.Packet
{
    class PackageProcess
    {
        /// <summary>
        ///     处理登陆包
        /// </summary>
        /// <param name="inpackage" type="Hi_Baidu.Packet.InPacket.LoginReplyPacket">
        ///     <para>
        ///         登陆包
        ///     </para>
        /// </param>
        public static void Process_Login_Package(LoginPacket inpackage)
        {
            String username = inpackage.GetUsername().Replace("*@^@*", "");
            String password = inpackage.GetPassword().Replace("*@^@*", "");
            LoginPacket.LoginState loginState = inpackage.GetLoginState();
            //判断登陆
            if (Globle.BLL_userManager.UserLogin(username, password))
            {
                ////////////////////////////////////////////////////////
                ///                      登录成功
                ////////////////////////////////////////////////////////
                //获取用户权限
                int Level = Globle.BLL_userManager.GetUserMession(username);
                String SessionCode = ProcessUserModel.AddUserToOnlineCollection(username, Level, inpackage, loginState);
                //反馈登陆成功
                ProcessLoginModel.ACK_SucessfulMessageToUser(username, Level, inpackage.GetTalkPort(),
                                                          inpackage.GetUserIpAddress(), SessionCode, loginState);
                //新建对于该用户的心跳超时器
                HeartBreathTimeOutEvent hreatBreathTimeOutEvent = new HeartBreathTimeOutEvent(username, 10000);
                //打入心跳超时器
                Globle.timeoutTimerManager.InstallTimer(hreatBreathTimeOutEvent);
            }
            else
            {
                ////////////////////////////////////////////////////////
                ///                      登录失败
                ////////////////////////////////////////////////////////
                //反馈登陆失败
                ProcessLoginModel.ACK_FailMessageToUser(username, inpackage.GetTalkPort(), inpackage.GetUserIpAddress());
            }
        }

        /// <summary>
        ///     处理获取自身请求包
        /// </summary>
        /// <param name="inpackage" type="UM_SERVER.Packet.InPacket.GetMySelfInfoPacket">
        ///     <para>
        ///         获取自身请求包
        ///     </para>
        /// </param>
        public static void Process_GetInfomation_Package(GetMySelfInfoPacket inpackage)
        {
            //获取当前用户是否经过了登录验证
            User.User user= Globle.userManager.GetUser(inpackage.GetUsername().Replace("*@^@*", ""));
            if (user != null)
            {
                ////////////////////////////////////////////////////
                ///            登录验证成功
                //////////////////////////////////////////////////// 
                Dictionary<String, String> DIC_USERINFO = null;
                //获取用户全部信息
                if ((DIC_USERINFO = Globle.BLL_userManager.GetFullUserInfo(inpackage.GetUsername())) != null)
                {
                    DIC_USERINFO.Add("LOGINLIVE", ((int)user.LoginLive).ToString());
                    //获取成功，并反馈
                    ProcessInfomationModel.ACK_SucessfulGetMySelfInfo(inpackage, DIC_USERINFO);
                }
                else
                {
                    //获取失败
                }
            }
            else
            {
                ////////////////////////////////////////////////////
                ///            登录验证失败
                //////////////////////////////////////////////////// 
            }
        }

        /// <summary>
        ///     处理获取分组信息包
        /// </summary>
        /// <param name="inpackage" type="UM_SERVER.Packet.InPacket.GetGroupPacket">
        ///     <para>
        ///         获取分组包
        ///     </para>
        /// </param>
        public static void Process_Group_Package(GetGroupPacket inpackage)
        {
            //获取当前用户是否经过了登录验证
            if (Globle.userManager.GetUser(inpackage.GetUsername()) != null)
            {
                ////////////////////////////////////////////////////
                ///            登录验证成功
                //////////////////////////////////////////////////// 
                String UserId = null;
                //获取用户全部信息
                if ((UserId = Globle.BLL_userManager.GetUserId(inpackage.GetUsername())) != null)
                {
                    //获取用户ID成功，开始获取分组信息
                    Dictionary<int, String> DIC_ITEMINFO = null;
                    //获取用户分组成功
                    if ((DIC_ITEMINFO = Globle.BLL_itemManager.GetItemByUserId(UserId)) != null)
                    {
                        ProcessInfomationModel.ACK_SucessfulGetItemInfo(inpackage, DIC_ITEMINFO);
                    }
                    else
                    {
                        //获取失败
                    }
                }
                else
                {
                    //获取失败
                }
            }
            else
            {
                ////////////////////////////////////////////////////
                ///            登录验证失败
                //////////////////////////////////////////////////// 
            }
        }

        /// <summary>
        ///     处理获取指定分组内好友的请求包
        /// </summary>
        /// <param name="inpackage" type="UM_SERVER.Packet.InPacket.GetFriendByGroupPacket">
        ///     <para>
        ///         获取指定分组内好友请求包
        ///     </para>
        /// </param>
        public static void Process_GetFriendByGroup_Package(GetFriendByGroupPacket inpackage)
        {
            //获取对应分组下的所有好友
            Dictionary<String,String> DIC_FRIENDINFO = Globle.BLL_friendManager.GetFriendByItemId(inpackage.GetItemId());
            //处理
            ProcessInfomationModel.ACK_SucessfulGetFriendIdByGroupId(inpackage, DIC_FRIENDINFO);
        }

        /// <summary>
        ///     处理获取指定好友信息的请求包
        /// </summary>
        /// <param name="inpackage" type="UM_SERVER.Packet.InPacket.GetFriendInfoPacket">
        ///     <para>
        ///         获取指定好友信息请求包
        ///     </para>
        /// </param>
        public static void Process_GetFriendInfo_Package(GetFriendInfoPacket inpackage)
        {
            //获得该好友详细信息
            Dictionary<String, String> DIC_FRIENDINFO = Globle.BLL_userManager.GetFullUserInfo(int.Parse(inpackage.GetFriendId()));
            User.User user = (User.User)Globle.userManager.GetMemberByKey(DIC_FRIENDINFO["USERNAME"]);
            if (user != null)
            {
                DIC_FRIENDINFO.Add("ONLINESTATE", "true");
                DIC_FRIENDINFO.Add("TALKPORT", user.TalkPort.ToString());
                DIC_FRIENDINFO.Add("VIDEOPORT", user.VideoPort.ToString());
                DIC_FRIENDINFO.Add("VOICEPORT", user.VoicePort.ToString());
                DIC_FRIENDINFO.Add("FILEPORT", user.TransferFilePort.ToString());
                DIC_FRIENDINFO.Add("IPADDRESS", user.IpAddress);
            }
            else
            {
                DIC_FRIENDINFO.Add("ONLINESTATE", "false");
                DIC_FRIENDINFO.Add("TALKPORT", "0");
                DIC_FRIENDINFO.Add("VIDEOPORT", "0");
                DIC_FRIENDINFO.Add("VOICEPORT", "0");
                DIC_FRIENDINFO.Add("FILEPORT", "0");
                DIC_FRIENDINFO.Add("IPADDRESS", "NONE");
            }
            //处理
            ProcessInfomationModel.ACK_SucessfulGetFriendInfo(inpackage, DIC_FRIENDINFO);
        }

        /// <summary>
        ///     处理用户修改个性签名请求包
        /// </summary>
        /// <param name="inpackage" type="UM_SERVER.Packet.InPacket.ModifyProdPacket">
        ///     <para>
        ///         修改个性签名请求包
        ///     </para>
        /// </param>
        public static void Process_ModifyProd_Package(ModifyProdPacket inpackage)
        {
            //修改个性签名
            if(Globle.BLL_userManager.ModifyUserProd(inpackage.GetUsername(),inpackage.GetProd()))
            {
                //修改成功
                UpdateProcessModel.ACK_SucessfulModifyProd(inpackage);
            }
            else
            {
                //修改失败
                UpdateProcessModel.ACK_FailModifyProd(inpackage);
            }
        }

        /// <summary>
        ///     处理更新用户挂起请求包
        /// </summary>
        public static void Process_UpdateUserInfo(UpdateUserInfoPacket inpackage)
        {
            //处理挂起
            if (Globle.BLL_userManager.Update(inpackage.GetUsername(), inpackage.GetDbFiled(), inpackage.GetNewValue()))
            {
                /////////////////////////////////////////////////////////
                ///                        更新成功
                /////////////////////////////////////////////////////////
                UpdateProcessModel.ACK_SucessfulUpdateUserInfo(inpackage);
            }
            else
            {
                /////////////////////////////////////////////////////////
                ///                        更新失败
                /////////////////////////////////////////////////////////
                UpdateProcessModel.ACK_FailUpdateUserInfo(inpackage);
            }
        }

        /// <summary>
        ///      处理更改用户在线状态请求包
        /// </summary>
        /// <param name="inpackage"></param>
        public static void Process_ChanageUserOnlineState(ChanageUserOnlineStatePacket inpackage)
        {
            User.User user = (User.User)Globle.userManager.GetMemberByKey(inpackage.GetUsername());
            //当前用户登陆了，并且在线状态有所更改
            if (user != null && user.LoginLive != inpackage.GetUserOnlineState())
            {
                //更新该用户的在线状态
                user.LoginLive = inpackage.GetUserOnlineState();
                ProcessUserModel.ACK_SucessfulChanageUserOnlineState(inpackage);
            }
            else if (user != null)
            {
                //直接成功
                ProcessUserModel.ACK_SucessfulChanageUserOnlineState(inpackage);
            }
        }

        /// <summary>
        ///     处理更新用户分组请求包
        /// </summary>
        /// <param name="inpackage">更新用户分组请求包</param>
        public static void Process_UpdateItem(UpdateItemPacket inpackage)
        {
            //更新成功
            if (Globle.BLL_itemManager.UpdateItem(inpackage.GetValue(), inpackage.GetItemId())) 
            {
                UpdateProcessModel.ACK_SucessfulUpdateItem(inpackage);
            }
            //更新失败
            else
            {
                UpdateProcessModel.ACK_FailUpdateItem(inpackage);
            }
        }

        /// <summary>
        ///     处理添加用户分组请求包
        /// </summary>
        /// <param name="inpackage">添加用户分组请求包</param>
        public static void Process_AddItem(AddItemPacket inpackage)
        {
            int ItemId = 0;
            //添加分组成功
            if ((ItemId =Globle.BLL_itemManager.AddItem(inpackage.GetUsername(), inpackage.GetValue())) > 0)
            {
                UpdateProcessModel.ACK_SucessfulAddItem(inpackage, ItemId);
            }
            //添加分组失败
            else
            {
                UpdateProcessModel.ACK_FailAddItem(inpackage, -1);
            }
        }

        /// <summary>
        ///     处理删除用户分组请求包
        /// </summary>
        /// <param name="inpackage">删除用户分组请求包</param>
        public static void Process_DeleteItem(DeleteItemPacket inpackage)
        {
            //删除成功
            if (Globle.BLL_itemManager.DeleteItem(inpackage.GetItemId()))
            {
                UpdateProcessModel.ACK_SucessfulDeleteItem(inpackage);
            }
            //删除失败
            else
            {
                UpdateProcessModel.ACK_FailDeleteItem(inpackage);
            }
        }

        /// <summary>
        ///     处理获取要添加用户的信息请求包
        /// </summary>
        /// <param name="inpackage">获取要添加用户的信息请求包</param>
        public static void Process_GetPostFriendInfo(GetPostFriendInfoPacket inpackage)
        {
            Dictionary<String,String> DIC_USERINFO = Globle.BLL_userManager.GetFullUserInfo(inpackage.GetFriendName());
            if (DIC_USERINFO != null)
            {
                //存在该用户
                FriendProcessModel.ACK_GetPostFriendInfo(inpackage, DIC_USERINFO);
            }
            else
            {
                //不存在该用户
                FriendProcessModel.ACK_CanNotFindPostFriend(inpackage);
            }
        }

        /// <summary>
        ///     处理添加好友请求包
        /// </summary>
        /// <param name="inpackage">添加好友请求包</param>
        public static void Process_AddFriend(AddFriendPacket inpackage)
        {
            User.User user = Globle.userManager.GetMemberByKey(inpackage.GetFriendName()) as User.User;
            //用户在线 --> 转发请求
            if (user != null)
            {
                FriendProcessModel.Redirect_PostAddFriend(inpackage, user);
            }
            //用户离线 --> 记录请求
            else
            {
            }
        }

        /// <summary>
        ///     处理添加好友结果包
        /// </summary>
        /// <param name="inpackage">添加好友结果包</param>
        public static void Process_PostAddFriendResult(PostAddFriendResultPacket inpackage)
        {
            //返回接受命令成功信息给发送用户
            FriendProcessModel.Retrun_PostAddFriendResult(inpackage);
            //对方允许了添加好友
            if (inpackage.GetResult())
            {
                //*****************************************************************   
                //                      双方写入好友
                //*****************************************************************
                Globle.BLL_friendManager.AddFriend(int.Parse(inpackage.GetItemId()), inpackage.GetUsername());
                Globle.BLL_friendManager.AddFriend(int.Parse(inpackage.GetFriendItemId()), inpackage.GetFriendName()) ;
                //*****************************************************************   
                //                      分发通知
                //*****************************************************************
                FriendProcessModel.Boardcast_AddFriendResult(inpackage.GetFriendName(), inpackage.GetUsername(), FriendProcessModel.BOARDCAST_ADDFIRNED.SUCESSFUL, inpackage.GetItemId(), Globle.BLL_userManager.GetUserId(inpackage.GetUsername()));
                FriendProcessModel.Boardcast_AddFriendResult(inpackage.GetUsername(), inpackage.GetFriendName(), FriendProcessModel.BOARDCAST_ADDFIRNED.SUCESSFUL, inpackage.GetFriendItemId(), Globle.BLL_userManager.GetUserId(inpackage.GetFriendName()));
            }
            //对方拒绝了添加好友
            else
            {
                FriendProcessModel.Boardcast_AddFriendResult(inpackage.GetFriendName(), inpackage.GetUsername(), FriendProcessModel.BOARDCAST_ADDFIRNED.FAIL, "-1", "-1");
            }
        }

        /// <summary>
        ///     处理删除好友请求
        /// </summary>
        /// <param name="inpackage">删除好友请求包</param>
        public static void Process_DeleteFriend(DeleteFriendPacket inpackage)
        {
            DeleteFriendTrigger deleteFriendTrigger = Globle.triggerManager.GetTriggerByKey("DeleteFriendTrigger") as DeleteFriendTrigger;
            //删除自身好友
            if (Globle.BLL_friendManager.DeleteFriend(int.Parse(inpackage.GetItemId()), inpackage.GetFriendName()))
            {
                //删除对方好友
                if (Globle.BLL_friendManager.DeleteFriend(Globle.BLL_itemManager.GetItemsByUserId(inpackage.GetFriendName()), int.Parse(Globle.BLL_userManager.GetUserId(inpackage.GetUsername()))))
                {
                    //分发删除成功结果
                    deleteFriendTrigger.Trigger(inpackage.GetUsername(), inpackage.GetFriendName(), DeleteFriendTrigger.DELETE_FRIEND_STATE.SUCESSFUL);
                    deleteFriendTrigger.Trigger(inpackage.GetFriendName(), inpackage.GetUsername(), DeleteFriendTrigger.DELETE_FRIEND_STATE.SUCESSFUL);
                }
                else
                {
                    deleteFriendTrigger.Trigger(inpackage.GetFriendName(), inpackage.GetUsername(), DeleteFriendTrigger.DELETE_FRIEND_STATE.FAIL);
                }
            }
            else
            {
                deleteFriendTrigger.Trigger(inpackage.GetUsername(), inpackage.GetFriendName(), DeleteFriendTrigger.DELETE_FRIEND_STATE.FAIL);
            }
        }

        /// <summary>
        ///     处理用户心跳请求包
        /// </summary>
        /// <param name="inpackage">用户心跳请求包</param>
        public static void Process_UserHeartBreath(UserHeartBreathPacket inpackage)
        {
            User.User user = Globle.userManager.GetUser(inpackage.GetUsername());
            if(user.LoginLive != inpackage.GetUserOnlineState())
            {
                user.LoginLive = inpackage.GetUserOnlineState();
            }
            //重置当前心跳用户超时器
            (Globle.timeoutTimerManager.GetMemberByKey(inpackage.GetUsername()) as TimeOutEvent).ReSet();
            //回馈用户心跳
            ProcessUserModel.ACK_UserHeartBreath(inpackage);
        }
    }
}
